package redis_kits

import (
	"errors"
	"github.com/go-redis/redis"
	"time"
)

type redisCluster struct {
	client *redis.ClusterClient
}

func (c *redisCluster) Set(key string,value interface{},timeout time.Duration) error {
	if _,err := c.client.Set(key,value,timeout).Result(); err != nil {
		return err
	}
	return nil
}

func (c *redisCluster) SetNX(key string,value interface{},timeout time.Duration) error {
	if _, err := c.client.SetNX(key, value, timeout).Result(); err != nil {
		return err
	}
	return nil
}

func (c *redisCluster) Delete(key ...string) error {
	if _, err := c.client.Del(key...).Result(); err != nil {
		return err
	}
	return nil
}

func (c *redisCluster) Incr(key string) (int64,error){
	return c.client.Incr(key).Result()
}

func (c *redisCluster) RPush(key string,value interface{}) error {
	_, err := c.client.RPush(key, value).Result()
	return err
}
func (c *redisCluster) LPush(key string,value interface{}) error {
	_, err := c.client.LPush(key, value).Result()
	return err
}

func (c *redisCluster) Subscribe(channel string) *redis.PubSub {
	return c.client.Subscribe(channel)
}

func (c *redisCluster) Publish(channel string,value string) error {
	return c.client.Publish(channel,value).Err()
}

func (c *redisCluster) Get(key string) string {
	value, err := c.client.Get(key).Result()
	if nil != err {
		return ""
	}
	return value
}

func (c *redisCluster) Ping() error {
	_,err := c.client.Ping().Result()
	return err
}

func (c *redisCluster) Exists (key string) (bool,error) {
	i,err := c.client.Exists(key).Result()
	if err != nil {
		return false,err
	}
	return i==1,nil
}

func (c *redisCluster) Pull(key string)([]string,error) {
	len,err := c.client.LLen(key).Result()
	if err != nil {
		return nil,err
	}
	if len > 0 {
		values,err := c.client.LRange(key,0,len).Result()
		if err != nil {
			return nil,err
		}
		return values,nil
	}
	return nil,nil
}
func (c *redisCluster) Pop(key string)([]string,error) {
	len,err := c.client.LLen(key).Result()
	if err != nil {
		return nil,err
	}
	if len > 0 {
		values,err := c.client.LRange(key,0,len).Result()
		if err != nil {
			return nil,err
		}
		result,err := c.client.Del(key).Result()
		if err != nil {
			return nil,err
		}
		if result != 1 {
			return nil,errors.New("result invalid")
		}
		return values,nil
	}
	return nil,nil
}
